package com.nuaa.service.repertory.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.nuaa.dao.overseas.inter.LocalDisDaoInter;
import com.nuaa.dao.repertory.inter.CartDaoInter;
import com.nuaa.dao.repertory.inter.ProDaoInter;
import com.nuaa.dao.repertory.inter.SubProDaoInter;
import com.nuaa.dao.repertory.inter.SubProRecordDaoInter;
import com.nuaa.domain.overseas.LocalCartEntity;
import com.nuaa.domain.overseas.LocalDisEntity;
import com.nuaa.domain.repertory.ProductInfoEntity;
import com.nuaa.domain.repertory.SubProRecordEntity;
import com.nuaa.domain.repertory.SubProductInfoEntity;
import com.nuaa.formmodel.LocalSubForm;
import com.nuaa.service.repertory.inter.ProInfoServiceInter;
import com.nuaa.utils.AjaxMsg;
import com.nuaa.utils.BusinessException;
import com.nuaa.utils.CustomCodeUtil;
import com.nuaa.utils.DataGrid;
import com.nuaa.utils.PageInfo;
/***
 * 商品管理
 * @author heaven
 *
 */
@Service("proInfoService")
public class ProInfoServiceImpl implements ProInfoServiceInter{
	@Resource(name="proInfoDao")
	private ProDaoInter proInfoDao;
	@Resource(name="subProInfoDao")
	private SubProDaoInter subProInfoDao;
	@Resource(name="cartDao")
	private CartDaoInter cartDao;
	@Resource(name="localDisDao")
	private LocalDisDaoInter localDisDao;
	@Resource(name="subProRecordDao")
	private SubProRecordDaoInter subProRecordDao;
	/***
	 * 获取所有商品信息
	 */
	@Override
	public DataGrid<Map<String, Object>> getProInfo(String customerNo,PageInfo pager) {
		StringBuilder sql=new StringBuilder();
		sql.append("select * from proInfo_tab ");
		sql.append(" where 1=1 ");
		if(customerNo!=null && !"".equals(customerNo)){
			sql.append(" and customer_no = '");
			sql.append(customerNo);
			sql.append("'");
		}
		System.out.println(sql);
		try{
			long total=proInfoDao .count(sql.toString());
			int []fm=pager.getFirstindexAndMaxindex();
			List<Map<String,Object>> list=proInfoDao.searchForMap(sql.toString(),fm[0],fm[1]," id desc ");
			return new DataGrid<Map<String, Object>>(total, list);
		}catch(Exception e){
			throw new BusinessException("获取信息出错！",e);
		}
	}
	/***
	 * 获取数量非零的所有商品信息
	 * 当前客户在查看时，所能看到的都是已经被管理员入库的，所谓入库就是对商品的数量进行修改为大于0的数
	 */
	@Override
	public DataGrid<Map<String, Object>> getNoZreoProInfo(String customerNo,PageInfo pager) {
		StringBuilder sql=new StringBuilder();
		sql.append("select * from sub_proInfo_tab ");
		sql.append(" where customer_no = '");
		sql.append(customerNo);
		sql.append("'");
		System.out.println(sql.toString());
		try{
			long total=subProInfoDao.count(sql.toString());
			int []fm=pager.getFirstindexAndMaxindex();
			List<Map<String,Object>> list=subProInfoDao.searchForMap(sql.toString(),fm[0],fm[1]," id desc ");
			return new DataGrid<Map<String, Object>>(total, list);
		}catch(Exception e){
			throw new BusinessException("获取信息出错！",e);
		}
	}
	/***
	 * 添加一条商品信息
	 */
	@Transactional
	@Override
	public AjaxMsg subProInfo(ProductInfoEntity entity) {
		AjaxMsg msg = new AjaxMsg();
		try{
			entity.setPro_no(CustomCodeUtil.getProNo(proInfoDao.getMaxId(entity.getClass())));
			this.proInfoDao.save(entity);
			msg.setMsg("添加入库成功！");
			msg.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			msg.setMsg("添加失败！");
			msg.setSuccess(false);
		}
		return msg;
	}
	/**
	 * 删除商品信息
	 */
	@Transactional
	@Override
	public AjaxMsg delProInfo(String proNos) {
		AjaxMsg msg = new AjaxMsg();
		String [] proNoArray = proNos.split(",");
		try{
			for (String str : proNoArray) {
				String sql1 = "delete from proInfo_tab where pro_no = '"+str+"'";
				String sql2 = "delete from sub_proInfo_tab where pro_no = '"+str+"'";
				this.proInfoDao.update(sql1);
				this.subProInfoDao.update(sql2);
			}
				msg.setSuccess(true);
				msg.setMsg("删除商品信息成功！");
			}catch (Exception e) {
				msg.setSuccess(false);
				msg.setMsg("删除失败！");
			}
			return msg;
	}
	@Transactional
	@Override
	public AjaxMsg delSubProInfo(String ids) {
		AjaxMsg msg = new AjaxMsg();
		String [] id = ids.split(",");
		try{
			for (String str : id) {
				this.subProInfoDao.delete(SubProductInfoEntity.class, Integer.parseInt(str));
			}
				msg.setSuccess(true);
				msg.setMsg("删除成功！");
			}catch (Exception e) {
				msg.setSuccess(false);
				msg.setMsg("删除失败！");
			}
			return msg;
	}
	
	/***
	 * 修改一条已入库商品信息
	 */
	@Transactional
	@Override
	public AjaxMsg modifyProInfo(SubProductInfoEntity entity) {
		AjaxMsg msg = new AjaxMsg();
		SubProductInfoEntity subEntity = subProInfoDao.find(SubProductInfoEntity.class,entity.getId());
		String oldFilePath = subEntity.getImage_name();
		String newFilePath = entity.getImage_name();
		if(newFilePath==null){
			entity.setImage_name(oldFilePath);
			System.out.println("old--"+oldFilePath);
		}
		try{
			entity.setCreate_tm(new Date());
			this.subProInfoDao.update(entity);
			msg.setMsg("修改成功！");
			msg.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			msg.setMsg("修改失败！");
			msg.setSuccess(false);
		}
		return msg;
	}
	/***
	 * 获取一条商品信息
	 */
	@Override
	public ProductInfoEntity getOneInfo(String id) {
		return this.proInfoDao.find(ProductInfoEntity.class, Integer.parseInt(id));
	}
	/**
	 * 获取一条已对应客户编码入库商品信息
	 */
	@Override
	public SubProductInfoEntity getOneSubProInfo(String id) {
		return this.subProInfoDao.find(SubProductInfoEntity.class, Integer.parseInt(id));
	}
	/**
	 * 提交入库
	 */
	@Transactional
	@Override
	public AjaxMsg subPutInPro(SubProductInfoEntity entity) {
		AjaxMsg msg = new AjaxMsg();
		try{
			entity.setCreate_tm(new Date());
			String sql = "select * from sub_proInfo_tab where pro_no ='"+entity.getPro_no()+"'";
			List<SubProductInfoEntity> list = subProInfoDao.search(SubProductInfoEntity.class, sql);
			if(list.size()==0){
				subProInfoDao.save(entity);
			}else{
				SubProductInfoEntity curEntity = list.get(0);
				curEntity.setPre_postage(entity.getPre_postage());
				curEntity.setPro_number(entity.getPro_number()+curEntity.getPro_number());
				subProInfoDao.update(curEntity);
			}
			/**
			 * 添加代码对入库记录进行操作
			 */
			SubProRecordEntity recordEntity = new SubProRecordEntity();
			recordEntity.setCreate_tm(new Date());
			recordEntity.setCustomer_no(entity.getCustomer_no());
			recordEntity.setHeight(entity.getHeight());
			recordEntity.setImage_name(entity.getImage_name());
			recordEntity.setLength(entity.getLength());
			recordEntity.setLoc_no(entity.getLoc_no());
			recordEntity.setLocation(entity.getLocation());
			recordEntity.setPre_postage(entity.getPre_postage());
			recordEntity.setPro_name(entity.getPro_name());
			recordEntity.setPro_no(entity.getPro_no());
			recordEntity.setPro_number(entity.getPro_number());
			recordEntity.setWarehouse(entity.getWarehouse());
			recordEntity.setWeight(entity.getWeight());
			recordEntity.setWidth(entity.getWidth());
			subProRecordDao.save(recordEntity);
			msg.setMsg("入库成功！");
			msg.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			msg.setMsg("入库失败！");
			msg.setSuccess(false);
		}
		return msg;
	}

	@Override
	public DataGrid<Map<String, Object>> getSubProInfo(PageInfo pager,String customerNo) {
		StringBuilder sql=new StringBuilder();
		sql.append("select * from sub_proInfo_tab ");
		sql.append(" where 1=1 ");
		if(customerNo!=null && !"".equals(customerNo)){
			sql.append(" and customer_no = '");
			sql.append(customerNo);
			sql.append("'");
		}
		try{
			long total=proInfoDao .count(sql.toString());
			int []fm=pager.getFirstindexAndMaxindex();
			List<Map<String,Object>> list=proInfoDao.searchForMap(sql.toString(),fm[0],fm[1]," id desc ");
			return new DataGrid<Map<String, Object>>(total, list);
		}catch(Exception e){
			throw new BusinessException("获取信息出错！",e);
		}
	}
	/***
	 * 客户提交当前商品至我的本地配送车
	 */
	@Transactional
	@Override
	public AjaxMsg addToCart(String ids) {
		AjaxMsg msg = new AjaxMsg();
		String [] id = ids.split(",");
		try{
			for (String str : id) {
				SubProductInfoEntity subPro = subProInfoDao.find(SubProductInfoEntity.class, Integer.parseInt(str));
				LocalCartEntity entity = new LocalCartEntity();
				entity.setCustomer_no(subPro.getCustomer_no());
				entity.setLoc_no(subPro.getLoc_no());
				entity.setImage_name(subPro.getImage_name());
				entity.setLocation(subPro.getLocation());
				entity.setPro_name(subPro.getPro_name());
				entity.setPro_no(subPro.getPro_no());
				entity.setWarehouse(subPro.getWarehouse());
				entity.setProInfoId(subPro.getId());
				cartDao.save(entity);
			}
				msg.setSuccess(true);
				msg.setMsg("添加成功！");
			}catch (Exception e) {
				msg.setSuccess(false);
				msg.setMsg("添加失败！");
			}
			return msg;
	}
	/**
	 * 获取所有我的本地配送车信息
	 */
	@Override
	public DataGrid<Map<String, Object>> getAllCartsInfo(PageInfo pager,String customerNo) {
		StringBuilder sql=new StringBuilder();
		sql.append("select * from local_cart_order ");
		sql.append(" where customer_no = '");
		sql.append(customerNo);
		sql.append("'");
		try{
			long total=cartDao.count(sql.toString());
			int []fm=pager.getFirstindexAndMaxindex();
			List<Map<String,Object>> list=cartDao.searchForMap(sql.toString(),fm[0],fm[1]," id desc ");
			return new DataGrid<Map<String, Object>>(total, list);
		}catch(Exception e){
			throw new BusinessException("获取信息出错！",e);
		}
	}
	/**
	 * 删除购物车中的记录
	 */
	@Transactional
	@Override
	public AjaxMsg delCart(String ids) {
		AjaxMsg msg = new AjaxMsg();
		String [] id = ids.split(",");
		try{
			for (String str : id) {
				this.cartDao.delete(LocalCartEntity.class, Integer.parseInt(str));
			}
				msg.setSuccess(true);
				msg.setMsg("删除成功！");
			}catch (Exception e) {
				msg.setSuccess(false);
				msg.setMsg("删除失败！");
			}
			return msg;
	}
	@Transactional
	@Override
	public AjaxMsg subFromCartToOrder(String ids,
			List<LocalSubForm> list) {
		AjaxMsg msg = new AjaxMsg();
		String [] id = ids.split(",");

		int cartId = Integer.parseInt(id[0]);
		int proInfoId = Integer.parseInt(id[1]);
		int startOrderNo = localDisDao.getMaxId(LocalDisEntity.class);
		try{
			SubProductInfoEntity subPro = subProInfoDao.find(SubProductInfoEntity.class, proInfoId);
			//统计所要提交的商品总数量
			int subNum = 0;
			for(LocalSubForm form : list){
				subNum+=form.getNum();
			}
			if(subNum>subPro.getPro_number()){
				msg.setSuccess(false);
				msg.setMsg("提交失败，该商品库存不足！");
				return msg;
			}
			for(LocalSubForm form : list){
				LocalDisEntity entity = new LocalDisEntity();
				String address = form.getAddress();
				entity.setDis_address(address);
				entity.setPro_number(form.getNum());
				entity.setReceiver(form.getReceiver());
				entity.setLength(subPro.getLength());
				entity.setWidth(subPro.getWidth());
				entity.setHeight(subPro.getHeight());
				entity.setWeight(subPro.getWeight());
				entity.setCustomer_no(subPro.getCustomer_no());
				entity.setLoc_no(subPro.getLoc_no());
				entity.setImage_name(subPro.getImage_name());
				entity.setLocation(subPro.getLocation());
				entity.setPro_name(subPro.getPro_name());
				entity.setPro_no(subPro.getPro_no());
				entity.setWarehouse(subPro.getWarehouse());
				entity.setCreate_tm(new Date());
				entity.setPostage((double)(subPro.getPre_postage()));
				entity.setBusiness_type("海外仓本地配送订单");
				entity.setOrder_no(CustomCodeUtil.getLocalDisOrderNo(startOrderNo++));
				localDisDao.save(entity);
			}
				//提交后要删除掉该本地配送车记录
				cartDao.delete(LocalCartEntity.class, cartId);
				msg.setSuccess(true);
				msg.setMsg("添加成功！");
			}catch (Exception e) {
				e.printStackTrace();
				msg.setSuccess(false);
				msg.setMsg("添加失败！");
			}
			return msg;
	}
	/**
	 * 获取所有入库记录信息
	 */
	@Override
	public DataGrid<Map<String, Object>> getAllSubProRecords(PageInfo pager, String pro_no, String pro_name,
			String customer_no, String tmFrom, String tmTo) {
		StringBuilder sql=new StringBuilder();
		sql.append("select * from sub_pro_record where 1=1 ");
		if(customer_no!=null && !"".equals(customer_no)){
			sql.append(" and customer_no ='");
			sql.append(customer_no);
			sql.append("'");
		}
		if(pro_no!=null && !"".equals(pro_no)){
			sql.append(" and pro_no ='");
			sql.append(pro_no);
			sql.append("'");
		}
		if(pro_name!=null && !"".equals(pro_name)){
			sql.append(" and pro_name ='");
			sql.append(pro_name);
			sql.append("'");
		}
		if(tmFrom!=null && !"".equals(tmFrom) && tmTo!=null && !"".equals(tmTo)){
			sql.append(" and create_tm >='");
			sql.append(tmFrom);
			sql.append("' and create_tm <= '");
			sql.append(tmTo);
			sql.append("'");
		}
		try{
			long total=subProRecordDao .count(sql.toString());
			int []fm=pager.getFirstindexAndMaxindex();
			List<Map<String,Object>> list=subProRecordDao.searchForMap(sql.toString(),fm[0],fm[1]," create_tm desc ");
			return new DataGrid<Map<String, Object>>(total, list);
		}catch(Exception e){
			throw new BusinessException("获取订单信息出错！",e);
		}
	}
	@Transactional
	@Override
	public AjaxMsg delSubProRecords(String ids) {
		AjaxMsg msg = new AjaxMsg();
		String [] id = ids.split(",");
		try{
			for (String str : id) {
				this.subProRecordDao.delete(SubProRecordEntity.class, Integer.parseInt(str));
			}
				msg.setSuccess(true);
				msg.setMsg("删除成功！");
			}catch (Exception e) {
				msg.setSuccess(false);
				msg.setMsg("删除失败！");
			}
			return msg;
	}
	@Override
	public List<Map<String,Object>> getAllRecordsProNo() {
		String sql = "select id,pro_no as text from sub_pro_record ";
		List<Map<String,Object>> list = subProRecordDao.searchForMap(sql);
		return list;
	}
}
